<?php namespace Home\Controller;
use Hdphp\Controller\Controller;
use \Common\Model\Cate;
use \Common\Model\Goods;
use \Common\Model\GoodsAttr;
use \Common\Model\TypeAttr;
class ListController extends Controller{
	public function index(){
		$cateModel=new Cate();
		$cid=Q('get.cid',0,'intval');
		$cate=$cateModel->where("pid=0")->get();
		// 显示商品属性
		$goodModel=new Goods();
		//获取所有自己和自己子集的cid
		$cids=$cateModel->getSon($cateModel->get(),$cid);
		$cids[]=$cid;

		$gid=$goodModel->where("category_cid IN (".implode(',',$cids).")")->lists('gid');
		// p($gid);
		//找到所有的gid对应的商品属性
		if($gid){
			$goodsAttrModle=new GoodsAttr;
			$goodsAttrData=$goodsAttrModle->where("goods_gid IN (".implode(',',$gid).")")
						  ->groupBy('gtvalue')
						  ->get();
			// 找到名称相同的分成一类
			$temp=[];
			foreach($goodsAttrData as $k=>$v){
				$temp[$v['type_attr_taid']][]=$v;
		}
			//找到类型属性里面的类型名称
			$typeAttrModle=new TypeAttr();
			 //组合名字和值
        	$finalAttr = [];
        foreach ($temp as $taid => $v){
            $finalAttr[] = [
                'name' => $typeAttrModle->where("taid=$taid")->pluck('taname'),
                'value'=> $v
            ];
        }
        View::with('finalAttr',$finalAttr);
        //筛选param获取全部的
        $num=count($finalAttr);
        $param=isset($_GET['param'])?explode('_', $_GET['param']):array_fill(0,$num,0);
        // p($param);
        View::with('param',$param);
        //筛选，设置自定义方法$gids(分类对应的所有商品)，$param(所选的商品属性对应的gtid)
        $finalGids = $this->filter($param,$gid);
        $goodsData=[];
	        if($finalGids){
	         // 获得对应商品 
	        	$goodsData=$goodModel->where("gid IN (". implode(',', $finalGids).")")->get();
	        	View::with('goodsData',$goodsData);
	        }else{
	        	View::with('goodsData',[]);
	        	
	        } 
	        // p($goodsData);
        }else{
        		View::with('goodsData',[]);
            	View::with('finalAttr',[]);
        }

		View::with('cate',$cate);
		
		View::make();
	}
	// 获得筛选后的商品属性对应的商品
	private function filter($param,$cidGid){
		// p($param);
		$goodsAttrModle=new GoodsAttr;
		$gidAttr=[];
		foreach ($param as $gtid) {
			if($gtid){
				$gtvalue=$goodsAttrModle->where("gtid=$gtid")->pluck('gtvalue');
				$gidAttr[]=$goodsAttrModle->where(['gtvalue'=>$gtvalue])->lists('goods_gid');
			}
		}
		// p($gidAttr);
		// 当有筛选的时候选择的
		if($gidAttr){
			$gid=$gidAttr[0];
			foreach ($gidAttr as $v) {
				$gid=array_intersect($v,$gid);
			}
			// 防止是其他分类的gid要再次取交集
			$finalGids=array_intersect($gid, $cidGid);
		}
		//全部不限的时候就是获取当前类下面的所有的商品
		else{
			$finalGids=$cidGid;
		}
		return $finalGids;

	}
}